package com.venusz.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 @EnableAutoConfiguration：这个注解是用来启动springboot中的自动配置项目，必须的加上，否则无法正常使用springboot默认配置的配置项目。
 @ComponentScan ：扫描controller层和service层中所有类上的注解(这个注解可以不加，因为组合注解@SpringBootApplication已经可以扫描)。
 @MapperScan("com.zxz.mapper") ：管理mybatis中所有mapper接口的代理对象。
 @EnableTransactionManagement(proxyTargetClass = true)：开启事务管理的注解。
 */
@SpringBootApplication
@EnableAutoConfiguration
@MapperScan("com.venusz.datasource.dao")
@EnableTransactionManagement(proxyTargetClass = true)
public class DatasourceApplication {

	public static void main(String[] args) {
		SpringApplication.run(DatasourceApplication.class, args);
	}


	/**
	 * 注册DruidServlet
	 * @return
	 */
	@Bean
	public ServletRegistrationBean druidServletRegistrationBean() {
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
		servletRegistrationBean.setServlet(new StatViewServlet());
		servletRegistrationBean.addUrlMappings("/druid/*");
		return servletRegistrationBean;
	}
	/**
	 * 注册DruidFilter拦截
	 * @return
	 */
	@Bean
	public FilterRegistrationBean duridFilterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new WebStatFilter());
		Map<String, String> initParams = new HashMap<String, String>();
		//设置忽略请求
		initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
		filterRegistrationBean.setInitParameters(initParams);
		filterRegistrationBean.addUrlPatterns("/*");
		return filterRegistrationBean;
	}
	/**
	 * 配置DruidDataSource
	 * @return
	 * @throws SQLException
	 */
	@Bean
	public DruidDataSource druidDataSource() throws SQLException {
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setUsername("root");
		druidDataSource.setPassword("123");
		druidDataSource.setUrl("jdbc:mysql://localhost:3306/test");
		druidDataSource.setMaxActive(100);
		druidDataSource.setFilters("stat,wall");
		druidDataSource.setInitialSize(10);
		return druidDataSource;
	}
}
